package com.atguigu.tingshu.common.login;/*
 * title:
 * author:
 * date:
 * description:
 * */

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class GuiGuLoginAspect {
    @Resource
    private RedisTemplate redisTemplate;

    @Around("@annotation(guiGuLogin)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint,GuiGuLogin guiGuLogin) throws Throwable{

        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("token");
        UserInfoVo userInfoVo=null;
        if (StringUtils.isNotBlank(token)){
             userInfoVo = (UserInfoVo)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        }
        if (guiGuLogin.required()&& (StringUtils.isBlank(token) || userInfoVo == null )){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        if (userInfoVo!=null){
            AuthContextHolder.setUserId(userInfoVo.getId());
            //传说这句有问题，先注释掉
//            AuthContextHolder.setUsername(AuthContextHolder.getUsername());
        }

        Object result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();
        return result;
    }
}
